package com.sta.oldman.ws;

import com.sta.oldman.config.GetHttpSessionConfig;
import com.sta.oldman.config.WebSocketConfig;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: LunBoWang
 * @description: websocket 服务器端
 * @date: 2025/7/15 下午8:40
 * @version: 1.0
 */
@ServerEndpoint(value = "/ws",configurator = GetHttpSessionConfig.class)
@Component
public class Endpoint {

    private static final Map<String,Session> onlineSessions = new ConcurrentHashMap<>();
    private HttpSession httpSession;

    /**
     * 建立websocket连接后被调用
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig config){
        //1.将session存入到map中
        this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        onlineSessions.put(httpSession.getId(),session);
    }

    @OnMessage
    public void onMessage(String message){
        //1.获取session
        Session session = onlineSessions.get(httpSession.getId());
        //2.将消息发送到客户端
        try {
            session.getBasicRemote().sendText(message);
        }  catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session){
        //1.将session从map中移除
        onlineSessions.remove(httpSession.getId());
    }
}
